<template>
    <div class="avatar" @click="showDialog">
        <img title="点击上传头像" class="img-cycle" :src="value"/>
        <el-dialog ref="dialog" title="头像" :visible.sync="visible" append-to-body width="570px">
            <div style="margin-bottom: 10px">
                <div style="height: 300px;width: 300px;display: inline-block;vertical-align: middle;">
                    <vueCropper
                        ref="cropper"
                        :img="option.img"
                        :outputSize="option.size"
                        :outputType="option.outputType"
                        :info="true"
                        :full="option.full"
                        :canMove="option.canMove"
                        :canMoveBox="option.canMoveBox"
                        :fixedBox="option.fixedBox"
                        :original="option.original"
                        :autoCrop="option.autoCrop"
                        :autoCropWidth="option.autoCropWidth"
                        :autoCropHeight="option.autoCropHeight"
                        :centerBox="option.centerBox"
                        :high="option.high"
                        :infoTrue="option.infoTrue"
                        :maxImgSize="option.maxImgSize"
                        :aspectRatio="1"
                        @realTime="realTime"
                        @imgLoad="imgLoad"
                        :enlarge="option.enlarge"
                        :mode="option.mode"
                        :limitMinSize="option.limitMinSize"
                    ></vueCropper>
                </div>
                <div class="show-preview" :style="previewStyle">
                    <div :style="previews.div">
                        <img :src="previews.url" :style="previews.img">
                    </div>
                </div>
            </div>
            <el-button icon="el-icon-upload" size="small" type="primary" @click="selectFile">选取文件</el-button>
            <input @change="uploadImg" type="file" accept=".gif,.jpg,.jpeg,.png,.bmp,.GIF,.JPG,.PNG" hidden
                   ref="uploadImg"/>
            <template #footer>
                <el-button size="mini" type="primary" @click="confirm">确认</el-button>
                <el-button size="mini" plain @click="cancel">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {VueCropper} from 'vue-cropper'
import fileApi from "@/api/file/fileApi";
import {mapMutations} from "vuex";

export default {
    name: "signle-pic",
    computed: {},
    props: {
        value: {
            type: String,
            default() {
                return '*'
            }
        }
    },
    components: {
        VueCropper
    },
    data() {
        return {
            // 当前用户的头像文件信息
            visible: false,
            // ---------------------- VueCropper相关
            // 预览信息
            previews: {},
            previewStyle: {},
            option: {
                // 图片的路径
                img: "",
                // 生成的图片质量
                size: 1,
                full: false,
                outputType: "png",
                canMove: true,
                // 截图框是否大小固定
                fixedBox: true,
                original: false,
                canMoveBox: true,
                autoCrop: true,
                // 只有自动截图开启 宽度高度才生效
                autoCropWidth: 180,
                autoCropHeight: 180,
                // 截图框是否限制在图片里
                centerBox: true,
                high: false,
                cropData: {},
                enlarge: 1,
                mode: 'contain',
                maxImgSize: 3000,
                limitMinSize: [100, 180]
            }
        }
    },
    methods: {
        ...mapMutations({
            setAvatar: 'user/setAvatar',
        }),
        showDialog() {
            this.option.img = this.value
            this.visible = true
        },
        handleError(err) {
            console.log(err)
        },
        // 文件选取
        selectFile() {
            console.log(this.$el)
            this.$refs.uploadImg.click()
        },
        uploadImg(e) {
            //上传图片
            var file = e.target.files[0];
            if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
                alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
                return false;
            }
            var reader = new FileReader();
            reader.onload = e => {
                let data;
                if (typeof e.target.result === "object") {
                    // 把Array Buffer转化为blob 如果是base64不需要
                    data = window.URL.createObjectURL(new Blob([e.target.result]));
                } else {
                    data = e.target.result;
                }
                this.option.img = data;
                this.$refs.uploadImg.value = ''
            };
            // 转化为base64
            // reader.readAsDataURL(file)
            // 转化为blob
            reader.readAsArrayBuffer(file);
        },
        confirm() {
            console.log(this.previews)
            this.$refs.cropper.getCropBlob((data) => {
                // do something
                let file = new File([data], 'avatar.png', {type: 'image/png'})
                fileApi.upload({file}).then(res => {
                    this.visible = false
                    this.$emit('on-success', res.data);
                })
            })
        },
        cancel() {
            this.visible = false
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 裁剪的实时变化事件
        realTime(data) {
            var previews = data;
            var h = 0.5;
            var w = 0.2;

            this.previewStyle = {
                width: previews.w + "px",
                height: previews.h + "px",
                overflow: "hidden",
                margin: "0",
                zoom: 200 / previews.h
            };
            this.previews = data;
        },
        imgLoad(msg) {
            console.log(msg);
        },
    },
    mounted() {
    }
}
</script>

<style lang="scss" scoped>
.avatar {
    height: 180px;
    width: 180px;
    display: inline-block;
    position: relative;
    text-align: center;

    &:hover:after {
        content: '+';
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        color: #eee;
        background: rgba(0, 0, 0, 0.5);
        font-size: 24px;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        cursor: pointer;
        line-height: 180px;
        border-radius: 50%;
    }
}

.img-cycle {
    border-radius: 50%;
}

.show-preview {
    display: inline-block;
    vertical-align: middle;
    margin-left: 20px;
}
</style>
